from django.db import models
from django.conf import settings
from stories.models import Story


class Comment(models.Model):
    """评论模型"""
    story = models.ForeignKey(
        Story,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name='故事'
    )
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name='作者'
    )
    content = models.TextField(verbose_name='内容')
    likes = models.IntegerField(default=0, verbose_name='点赞数')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'comments'
        verbose_name = '评论'
        verbose_name_plural = '评论'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['-created_at']),
            models.Index(fields=['story']),
        ]
    
    def __str__(self):
        return f'{self.author.name}: {self.content[:20]}'


class Like(models.Model):
    """点赞模型"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='likes',
        verbose_name='用户'
    )
    story = models.ForeignKey(
        Story,
        on_delete=models.CASCADE,
        related_name='story_likes',
        null=True,
        blank=True,
        verbose_name='故事'
    )
    comment = models.ForeignKey(
        Comment,
        on_delete=models.CASCADE,
        related_name='comment_likes',
        null=True,
        blank=True,
        verbose_name='评论'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'likes'
        verbose_name = '点赞'
        verbose_name_plural = '点赞'
        # 确保用户对同一故事或评论只能点赞一次
        constraints = [
            models.UniqueConstraint(
                fields=['user', 'story'],
                condition=models.Q(story__isnull=False),
                name='unique_story_like'
            ),
            models.UniqueConstraint(
                fields=['user', 'comment'],
                condition=models.Q(comment__isnull=False),
                name='unique_comment_like'
            ),
        ]
        indexes = [
            models.Index(fields=['user', 'story']),
            models.Index(fields=['user', 'comment']),
        ]
    
    def __str__(self):
        if self.story:
            return f'{self.user.name} 点赞了故事 {self.story.title}'
        elif self.comment:
            return f'{self.user.name} 点赞了评论 {self.comment.id}'
        return f'点赞 {self.id}'
    
    def clean(self):
        """验证：story和comment必须有且只有一个"""
        from django.core.exceptions import ValidationError
        if not self.story and not self.comment:
            raise ValidationError('必须指定story或comment')
        if self.story and self.comment:
            raise ValidationError('不能同时指定story和comment')


class Bookmark(models.Model):
    """收藏模型"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='bookmarks',
        verbose_name='用户'
    )
    story = models.ForeignKey(
        Story,
        on_delete=models.CASCADE,
        related_name='bookmarked_by',
        verbose_name='故事'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='收藏时间')
    
    class Meta:
        db_table = 'bookmarks'
        verbose_name = '收藏'
        verbose_name_plural = '收藏'
        unique_together = ['user', 'story']  # 防止重复收藏
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'story']),
            models.Index(fields=['-created_at']),
        ]
    
    def __str__(self):
        return f'{self.user.name} 收藏了 {self.story.title}'
